<template>
  <div>
    <!-- 页面头部 -->
    <div class="page-header flex align-center space-between">
      <div class="font-weight--lg font-size--lg">
        <span v-show="currentNode">{{ currentNode ? currentNode.name : '' }}</span>
        <span>（{{ pageCount }}项）</span>
      </div>
    </div>
    <!-- 页面内容 -->
    <div class="page-body">
      <el-form :model="queryForm" :inline="true" ref="queryFormRef" size="small" @submit.native.prevent>
        <el-form-item>
          <el-input size="small" placeholder="请输入权限名" v-model.trim="queryForm.search" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-select size="small" placeholder="请选择状态" v-model="queryForm.status">
            <el-option v-for="item in statusDataList" :key="'status' + item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="small" class="width_104" type="primary" @click="getPageDataList()">查询</el-button>
          <el-button size="small" class="width_104" @click="resetOption()">重置</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-button size="mini" type="success" icon="el-icon-document-add" @click="configOption()" v-if="roleBtns.includes('sys:department:addrole') || $store.getters.isAdmin" :disabled="currentNode && !currentNode.isEnable">配置权限组</el-button>
        <el-button size="mini" type="danger" icon="el-icon-delete" @click="memberRemoveOption()" v-if="roleBtns.includes('sys:department:delrole') || $store.getters.isAdmin">批量删除</el-button>
      </div>
      <el-table class="margin_top_20" stripe :data="pageData" :header-cell-style="tableHeaderStyle" row-key="id" v-loading="loading" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="42"></el-table-column>
        <el-table-column prop="roleName" label="权限名称"></el-table-column>
        <el-table-column prop="remark" label="权限描述">
          <template slot-scope="scope">
            <div class="text-ellipsis_2" :title="scope.row.remark">{{scope.row.remark}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="成员数"></el-table-column>
        <el-table-column prop="roleStatus" label="状态">
          <template slot-scope="scope">
            <!-- <el-switch @change="changeStatus($event, scope.row)" :value="scope.row.roleStatus == 0"></el-switch> -->
            <el-tag type="success" v-if="scope.row.roleStatus == 0">启用</el-tag>
            <el-tag type="danger" v-else>禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <button class="my-btn my-btn--mini my-btn--primary plain" @click="showPower(scope.row)" v-if="roleBtns.includes('sys:department:show') || $store.getters.isAdmin">查看</button>
            <button class="my-btn my-btn--mini my-btn--danger plain" @click="removeDepartChildOption([scope.row.id])" v-if="roleBtns.includes('sys:department:delrole') || $store.getters.isAdmin">删除</button>
          </template>
        </el-table-column>
      </el-table>

      <div class="text-center">
        <br>
        <el-pagination background @size-change="handleSizeChange" @current-change="handlePagingChange" :current-page="pageIndex" :page-sizes="pageSizes"
          :page-size="pageSize" :layout="paginationLayout" :total="pageCount">
        </el-pagination>
      </div>
    </div>

    <power-group :visible.sync="isShowModel" :node="currentNode" :name="title" @update="getPageDataList()"></power-group>

    <power-show :visible.sync="isShowDetailModel" :item-id="editPowerId" :title="title"></power-show>
  </div>
</template>

<script>
import Setting from '@/settings';
import { mapGetters } from 'vuex';
import { GetDepartmentPowerList, GetDepartmentChannelList, RemoveRoleOnDepart, UpdateUserStatus, DeleteDepartmentChannel } from '@/views/user-management/services/index';
import PowerGroup from '@/views/user-management/components/powerGroup';
import PowerShow from '@/views/user-management/components/powerShow';
import ChannelGroup from '@/views/user-management/components/channelGroup';

export default {
  components: {
    PowerGroup,
    PowerShow,
    ChannelGroup
  },
  props: {
    currentNode: {
      type: Object,
      default: null
    },
    treeData: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      title: '',
      queryForm: {
        search: '',
        status: '',
      },
      pageIndex: 1,
      pageSize: Setting.defaultTablePaginationSize,
      pageSizes: Setting.tablePaginationSizes,
      tableHeaderStyle: Setting.tableHeaderStyle,
      paginationLayout: Setting.tablePaginationLayout,
      pageData: [],
      pageCount: 0,
      loading: false,
      isShowModel: false,
      isShowDetailModel: false,
      multipleSelection: [],
      statusDataList: [
        { value: '', label: '全部' },
        { value: '0', label: '启用' },
        { value: '1', label: '禁用' },
      ],
      editPowerId: null,
      userInfo: JSON.parse(this.$store.getters.userInfo)
    }
  },
  watch: {
    currentNode: {
      immediate: true,
      handler: function (newValue) {
        if (!newValue) return;
        this.getPageDataList();
      }
    }
  },
  computed: {
    ...mapGetters(['roleBtns'])
  },
  methods: {
    showPower(rowData) {
      this.title = rowData.roleName;
      this.editPowerId = rowData.id;
      this.isShowDetailModel = true;
    },
    memberRemoveOption() {
      if (!this.multipleSelection || !this.multipleSelection.length) {
        this.$message.warning('请选择需要删除的权限!');
        return;
      }
      this.removeDepartChildOption(this.multipleSelection.map(item => item.id));
    },
    removeDepartChildOption(nodeIds) {
      this.$confirm('此操作将解除当前权限组与部门之间的关系, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        closeOnPressEscape: false,
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            RemoveRoleOnDepart({ roleIds: nodeIds, departmentId: this.currentNode.id })
              .then(data => {
                instance.confirmButtonLoading = false;
                if (data.code == 200) {
                  this.$message.success('解除成功!');
                  done()
                } else {
                  this.$message.success('解除失败!');
                }
              })
              .catch(error => {
                instance.confirmButtonLoading = false;
              })
          } else {
            done();
          }
        }
      }).then(() => {
        this.getPageDataList();
      })
    },
    changeStatus(event, rowData) {
      this.loading = true;
      UpdateUserStatus({ id: rowData.id })
        .finally(() => (this.loading = false))
        .then(data => {
          if (data.code == 200) {
            this.$message.success(event ? '启用成功!' : '禁用成功!');
            rowData.roleStatus = event ? 0 : 1;
          } else {
            this.$message.error(event ? '启用失败!' : '禁用失败!');
          }
        })
        .catch(error => {
          this.$message.error(error);
        })
    },
    configOption() {
      this.editPowerId = null;
      this.title = '添加成员';
      this.isShowModel = true;
    },
    handleSelectionChange(selectlist) {
      this.multipleSelection = selectlist;
    },
    handlePagingChange(event) {
      this.pageIndex = event;
      this.getPageDataList();
    },
    handleSizeChange(event) {
      this.pageIndex = 1;
      this.pageSize = event;
      this.getPageDataList();
    },
    getPageDataList() {
      this.loading = true
      GetDepartmentPowerList({
        proId: 4,
        depId: this.currentNode.id,
        search: this.queryForm.search,
        roleStatus: this.queryForm.status,
        pageNum: this.pageIndex,
        pageSize: this.pageSize
      })
        .finally(() => (this.loading = false))
        .then(data => {
          if (data.code == 200) {
            this.pageData = data.data.list;
            this.pageCount = data.data.total;

            if ((!data.data.list || !data.data.list.length) && this.pageIndex > 1) {
              this.pageIndex = 1;
              this.getPageDataList();
            }
          }
        })
    },
    resetOption() {
      this.queryForm.search = '';
      this.queryForm.status = '';
      this.getPageDataList();
    }
  }
}
</script>
<style lang="scss" scoped>
.width_104 {
  width: 104px;
}
</style>
